#include "global.h"
#include "logic_state.h"
#include "logic_state_game.h"
#include "logic_manager.h"
#include "gui_button.h"
#include "gui_manager.h"
#include "physics_manager.h"
#include "scene_manager.h"
#include "pass_manager.h"
#include "gui_enum.h"

logic_state_game::logic_state_game()
: mouse_down(false)
, keep_time(0.0f)
, hit_offset_coef(0.25f)
{
	gui_manager::get_instance()->add_button(GAMING_BUTTON_GUI_GROUP, BACK_TO_SELECT_BUTTON, "media/fanhuiguanqiaxuanze.png", 550, 0, 250, 50);
}

logic_state_game::~logic_state_game()
{

}

void logic_state_game::update(float dt)
{
	gui_manager::get_instance()->get_gui()->Update(dt);
	physics_manager::get_instance()->update_physics_logic(dt);
	pass_manager::get_instance()->update_keep_time(keep_time);

	if (mouse_down)
	{
        keep_time = 0.0f;
	}
	else
	{
		//the goal entity must have only one shape
		cpShape* s = scene_manager::get_instance()->get_goal_entity()->shapes[0];
		//goal logic info
		goal_info* g = scene_manager::get_instance()->get_goal_info();
		//(cx,cy) is goal image center positon
		int cx =  g->pos.x + g->width / 2;
		int cy =  g->pos.y + g->height / 2;
		//get 4 point around center positon and check is there goal image 
		if (physics_manager::get_instance()->shape_query(s, cx-g->width*hit_offset_coef, cy-g->height*hit_offset_coef) &&
			physics_manager::get_instance()->shape_query(s, cx-g->width*hit_offset_coef, cy+g->height*hit_offset_coef) &&
			physics_manager::get_instance()->shape_query(s, cx+g->width*hit_offset_coef, cy+g->height*hit_offset_coef) &&
			physics_manager::get_instance()->shape_query(s, cx+g->width*hit_offset_coef, cy-g->height*hit_offset_coef)  )
		{
			keep_time += dt;
			if (keep_time >= 1.2f)
			{
				pass_manager::get_instance()->pass_scene();
				logic_manager::get_instance()->change_state_to(STATE_SCENE_SELECT);
			}
		}
		else
		{
			keep_time = 0.0f;
		}
	}

	if (hge->Input_KeyUp(HGEK_LBUTTON))
	{
		mouse_down = false;
		physics_manager::get_instance()->left_mouse_up();
	}

	if (hge->Input_KeyDown(HGEK_LBUTTON))
	{
		mouse_down = true;
		physics_manager::get_instance()->left_mouse_down();
	}

	if (gui_manager::get_instance()->get_button(BACK_TO_SELECT_BUTTON)->GetState() == GUI_BUTTON_UP)
	{
		logic_manager::get_instance()->change_state_to(STATE_SCENE_SELECT);
	}

	//if (hge->Input_KeyDown(HGEK_P))
	//{
	//	pass_manager::get_instance()->pass_scene();
	//	logic_manager::get_instance()->change_state_to(STATE_SCENE_SELECT);
	//}
}

void logic_state_game::enter()
{
    keep_time = 0.0f;
	scene_manager::get_instance()->set_screen_fade_inout(SCREEN_FADE_IN);
	gui_manager::get_instance()->only_active_group(GAMING_BUTTON_GUI_GROUP);
}

void logic_state_game::exit()
{
    scene_manager::get_instance()->clear_scene();
}